var final_element_index;

/* 
	Generates the mt single_compound_element list.
*/
function mt_single_compound(url_read, url_write, mql, properties, display_num){
	final_element_index = 0;
			
 	// Get the information from freebase
	perform_freebase_read(
		url_read,
		mql,
		function (msg) {
		
			var topic = null;
			topic = msg.result[0];
	        if (!topic) return;
	        
	        var h_topics = '';
	        
	        // Go through and get all of the topics and add them to the list
	        properties.parent_list = $('#list_vals');
	        var topics = msg.result;
	     
	     	// Tell the user how may questions remain
	        var num_remaining_topics = topics.length;
	        var num_topics_string = ''+num_remaining_topics;
	        $("#num_topics").text(num_topics_string);
	        
	        // Create indexes that randomize the ordering of the query results:
	        var random_indexes = [];
	        for(var i=0; i<topics.length; i++){
	        	random_indexes[i] = i;
	        }
	        fisherYates(random_indexes);
	        
	        // Add the elements to the queue	        
	        for(var i=0; i<display_num && i<random_indexes.length; i++){
	        	addElement(topics, properties, random_indexes, display_num);
	        }
		},
		function(m){}
	);

	
}

/* 
	Adds a single element to the bottom of the list
 */
function addElement(element_list, properties, indexes, display_num){
	var index = final_element_index + 1;
	var element = element_list[indexes[index]];
	var name = element.name;
	var guid = element.guid;
	var id = replaceAll(name, ' ', '-')
	id = id.replace('.', '')
	id = id.replace(',', '')
	
	var website = element["/common/topic/webpage"];

	var post_command = properties.post_command;
	var topic1_guid = properties.topic1_guid; 
	var topic1_property = properties.topic1_property;
	var submit1_name = properties.submit1_name;
	var submit1_id = properties.submit1_id;
	var submit2_name = properties.submit2_name;
	var submit2_id = properties.submit2_id;
	
	var parent_list = properties.parent_list;
	
	// Data that is needed to generate text for the box        	
	var data = Object;
	data.website = website;
	
	// Create the element
	var e_box_text = properties.generate_mt_text(name, data); // dynamically generate text for the text box.
		
	var e_html = '<div id="id_'+id+'">';
	e_html += '<div style="width:400px;height:100px;border:1px solid black;"><strong><a href="'+properties.biov_url+name+'" "target="_blank">'+name+'</a></strong>';
	e_html += '<br></br><br></br>'
	e_html += '<div>'
	e_html += '<input type="hidden" name="index" value="'+index+'" id="index_'+id+'"/>';
	e_html += '<input type="hidden" name="topic_name" value="'+name+'" id="topic_name_'+id+'"/>';
	e_html += '<input type="hidden" name="topic_guid" value="'+guid+'" id="guid_'+id+'"/>';
	e_html += sec_element_html(id, 'Website', 'http://');
	e_html += '</div>';
	e_html += '<br></br>'
	e_html += e_box_text;
	e_html += '</div>';
	e_html += '<input type="submit" id="submit_'+id+'" value="submit" /> <input type="button" id="skip_'+id+'" value="Skip" />'
	e_html += '<br></br><br></br>';
	e_html += '</div>';
	//comp_html += '<br></br>'

	parent_list.append($(e_html));
	final_element_index = final_element_index + 1;

	// Bind controllers to the buttons:
	$('#submit_'+id).bind('click',
		function (e,data) {
			// Get the current topic's freebase topic_id
			var html_id = $(this).get(0).id;
			html_id = html_id.replace(/submit_/, "");							
			var topic_guid = $('#guid_'+html_id).val();
			var topic_name = $('#topic_name_'+html_id).val();
			
			// Get the value from the form and write to Freebase:
			var value = $('#secID_'+html_id).val();
	
			// Validate it as a url
			if(isUrl(value)){	
			
				// Write to Freebase
				submit_sec_element(value, html_id, topic_name, topic_guid, properties)
				
				//Move to the next element
				exchangeElement(html_id,element_list, properties, indexes, display_num);
			} else {
				alert(value + ' is not a valid url (the url must have "http://", etc.)');
			}
		}
	);
	        	
	// Bind controllers to the buttons:
	$('#skip_'+id).bind('click',
		function (e,data) {
			//var active = .accordion('option', 'active');
			
			//Move to the next element
			var html_id = $(this).get(0).id;
			html_id = html_id.replace(/skip_/, "");	
			exchangeElement(html_id, element_list, properties, indexes, display_num);
		}
	);
}

function replaceAll(text, strA, strB) {
    return text.replace(new RegExp(strA,"g"), strB);
}

/* 
Removes the given element, and places another one at the bottom of the queue.
 */
function exchangeElement(id,element_list,properties, indexes, display_num){
	//var new_index = parseFloat($('#index_'+id).val()) + 1;	
	$('#id_'+id).remove();
	addElement(element_list, properties, indexes);
	var num_remaining_topics = indexes.length - final_element_index + display_num;
	$("#num_topics").text(''+num_remaining_topics);
	return final_element_index;
}

function write_to_freebase(post_command, topic1_guid, topic1_property, topic2_name, topic2_id){
	// Write the data to freebase:
	var data = new Object();
	data["topic1_id"] = topic1_guid;
    data["topic1_property"] = topic1_property;
	data["topic2_add_names"] = topic2_name;
    data["topic2_add_ids"] = topic2_id;
    data["topic2_create_new"] = "false";
    data["topic2_remove_ids"] = "";
    data["topic2_type"] = "";
    data["topic2_type_for_create"] = "";
	
	$.ajax({
		type: "POST",
		url: post_command,
		data: data,
		success: function(m) {
			if (console && console.log) {
				console.log(m);
				perform_touch(freebase_domain);
			}
		},
		error: function(m) {
		},
		dataType: "text",
		cache: false
	});	

}

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}